package com.atguigu.demo.controller;

import com.atguigu.demo.entity.Employee;
import com.atguigu.demo.service.api.EmpService;
import com.atguigu.demo.utils.R;
import jakarta.annotation.Resource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class Controller03Data {

    public Controller03Data() {
        System.out.println("Controller03Data 创建对象了~~~");
    }

    @Resource
    private EmpService empService;

    @RequestMapping("/save/emp")
    public R saveEmp(@Validated @RequestBody Employee employee, BindingResult bindingResult) {

        // 获取绑定操作是否有错误
        boolean hasErrors = bindingResult.hasErrors();

        if (hasErrors) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();

            String finalMessage = fieldErrors.stream()
                    .map(fieldError -> fieldError.getField() + ":" + fieldError.getRejectedValue() + ":" + fieldError.getDefaultMessage())
                    .reduce((prevValue, nextValue) -> prevValue + ";" + nextValue)
                    .get();

            return R.fail("[校验失败]" + finalMessage);

        } else {

            return R.ok("校验成功：" + employee.toString() + " " + empService);
        }

    }

}
